//
//  MJTStatusPictureView1.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/15.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit
//配图cell重用标记
private let PictureViewCellIdentifier = "PictureViewCellIdentifier"
//每项间隔
private let itemMargin: CGFloat = 5
//每项的宽度
private  let itemWight = (ScreenWidth - 2 * HomeCellMargin - 2 * itemMargin) / 3
//配图信息
class MJTStatusPictureView1: UICollectionView {
    //设置数据源
    var picURLs:[MJTStatusPictureInfo]? {
        didSet {
            //显示个数
            messageLabel.text = "\(picURLs?.count ?? 0)"
            //根据图片个数计算高度
            let size = calcSizeWithCount(picURLs?.count ?? 0)
//            self.snp_makeConstraints { (make) -> Void in
//                make.size.equalTo(size)

//            }
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            //刷新数据
            self.reloadData()
        }

    }
    // 懒加载控件
    private lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.yellowColor(), fontSize: 30)
        return label
    }()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        //  设置大小
        flowLayout.itemSize = CGSize(width: itemWight, height: itemWight)
        //  水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        //  垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI() {
        //注册cell
        registerClass(MJTStatusPictureViewCell.self, forCellWithReuseIdentifier: PictureViewCellIdentifier)
        //设置数据源代理
        dataSource = self
        //设置代理
        delegate = self

        addSubview(messageLabel)
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }

    }
    //根据图片个数计算图片大小
    private func calcSizeWithCount(count: Int) -> CGSize {
        //计算列数
        let cols = count > 3 ? 3 : count
        //计算行数
        let rows = (count - 1) / 3 + 1
        //计算宽高
        let width = CGFloat(cols) * itemWight + CGFloat(cols - 1) * itemMargin
        let height = CGFloat(rows) * itemWight + CGFloat(rows - 1) * itemMargin
        //返回大小
        let size = CGSize(width: width, height: height)
        return size
    }
}
extension MJTStatusPictureView1: UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        print(picURLs?.count ?? 0)
        return picURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = dequeueReusableCellWithReuseIdentifier( PictureViewCellIdentifier, forIndexPath: indexPath) as! MJTStatusPictureViewCell
//        let cell = dequeueReusableCellWithReuseIdentifier( PictureViewCellIdentifier, forIndexPath: indexPath)
        cell.picInfo = picURLs![indexPath.item]
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //        SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
        //        photoBrowser.delegate = self;
        //        photoBrowser.currentImageIndex = indexPath.item;
        //        photoBrowser.imageCount = self.modelsArray.count;
        //        photoBrowser.sourceImagesContainerView = self.collectionView;
        //
        //        [photoBrowser show];
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = picURLs!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
}
//实现代理协议
extension MJTStatusPictureView1: SDPhotoBrowserDelegate {
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlStr = picURLs![index].thumbnail_pic?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: urlStr!)
    }
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)

        let cell = self.cellForItemAtIndexPath(indexPath) as! MJTStatusPictureViewCell

        return cell.imageView.image

    }
}
//  自定义配图cell
class MJTStatusPictureViewCell: UICollectionViewCell {
    //  设置模型
    var picInfo: MJTStatusPictureInfo? {
        didSet {
            if let imageUrl = picInfo?.thumbnail_pic {
                imageView.sd_setImageWithURL(NSURL(string: imageUrl), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                //  可以抽取成一句代码
                gifImageView.hidden = !imageUrl.hasSuffix(".gif")
            }
        }
    }
    // MARK: -懒加载控件
    //  配图的图片
    private lazy var imageView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  保证原始图片比例显示, 图片会超出
        view.contentMode = UIViewContentMode.ScaleAspectFill
        //  剪切超出多余部分的图片
        view.clipsToBounds = true
        return view
    }()
    //  gif图片
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //  添加控件设置约束
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(imageView)
            make.bottom.equalTo(imageView)
        }
    }
    
    
    
}